package com.example.technology.lovedemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 类描述：
 * 创建人：tgw
 * 创建时间：2020/8/12
 * 修改备注：
 */
public class LoveThree extends RelativeLayout {
    private Context mContext;
    float[] num = {-30, -20, 0, 20, 30};//随机心形图片角度
    private int[] icons = new int[4];
    private int mWidth;
    private int mHeight;
    private Canvas mCanvas;
    private Timer delayTimer;
    private TimerTask timeTask;
    long mCurTime = 0;
    long mLastTime = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            praiseRequest(mClickCount);
            delayTimer.cancel();
            super.handleMessage(msg);
        }
    };

    public LoveThree(Context context) {
        super(context);
        initView(context);
    }

    public LoveThree(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public LoveThree(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
//
        this.mCanvas =canvas;
        final ImageView imageView = new ImageView(mContext);
        LayoutParams params = new LayoutParams(100, 100);

        params.leftMargin = getWidth() - 200;
        params.topMargin = getHeight() / 2 - 300;
        icons[0] =R.drawable.heart_red;
        icons[1] = R.mipmap.zan1;
        icons[2] = R.mipmap.zan2;
        icons[3] = R.mipmap.zan3;

        imageView.setImageDrawable(getResources().getDrawable(icons[new Random().nextInt(4)]));
        imageView.setLayoutParams(params);
        addView(imageView);

        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "这里是点击爱心的动画，待展示", Toast.LENGTH_SHORT).show();
            }
        });

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scale(imageView, "scaleX", 2f, 0.9f, 100, 0))
                .with(scale(imageView, "scaleY", 2f, 0.9f, 100, 0))
                .with(rotation(imageView, 0, 0, num[new Random().nextInt(4)]))
                .with(alpha(imageView, 0, 1, 100, 0))
                .with(scale(imageView, "scaleX", 0.9f, 1, 50, 150))
                .with(scale(imageView, "scaleY", 0.9f, 1, 50, 150))
                .with(translationY(imageView, 0, -600, 800, 400))
                .with(alpha(imageView, 1, 0, 300, 400))
                .with(scale(imageView, "scaleX", 1, 3f, 700, 400))
                .with(scale(imageView, "scaleY", 1, 3f, 700, 400));

        if (  mWidth >0 && mHeight >1) {
            animatorSet = getAnimatorSet(imageView);
            animatorSet.start();
        }
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                removeViewInLayout(imageView);
            }
        });
        mCurTime = System.currentTimeMillis();
        if (mCurTime - mLastTime < 2000) {
            super.dispatchDraw(canvas);
        } else {
            Toast.makeText(mContext,"时间到了",Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        dispatchDraw(mCanvas);
        mLastTime = System.currentTimeMillis();
        mWidth = (int) (event.getRawX() - (event.getRawX()-event.getX()));
        mHeight = (int) (event.getRawY() - (event.getRawY()-event.getY()));
//        Log.d("tgw", "onTouchEvent: mWidth:"+mWidth+"--mHeight:"+mHeight+"--event.getRawY():"+event.getRawY()+"--event.getY():"+event.getY());
//        final ImageView imageView = new ImageView(mContext);
//        LayoutParams params = new LayoutParams(300, 300);
////        params.leftMargin = (int) event.getX() - 150;
////        params.topMargin = (int) event.getY() - 300;
//        icons[0] =R.drawable.heart_red;
//        icons[1] = R.mipmap.zan1;
//        icons[2] = R.mipmap.zan2;
//        icons[3] = R.mipmap.zan3;
//
//        imageView.setImageDrawable(getResources().getDrawable(icons[new Random().nextInt(4)]));
////        imageView.setImageDrawable(getResources().getDrawable(R.drawable.heart_red));
//        imageView.setLayoutParams(params);
//        addView(imageView);

//        AnimatorSet animatorSet = new AnimatorSet();
//        animatorSet.play(scale(imageView, "scaleX", 2f, 0.9f, 100, 0))
//                .with(scale(imageView, "scaleY", 2f, 0.9f, 100, 0))
//                .with(rotation(imageView, 0, 0, num[new Random().nextInt(4)]))
//                .with(alpha(imageView, 0, 1, 100, 0))
//                .with(scale(imageView, "scaleX", 0.9f, 1, 50, 150))
//                .with(scale(imageView, "scaleY", 0.9f, 1, 50, 150))
//                .with(translationY(imageView, 0, -600, 800, 400))
//                .with(alpha(imageView, 1, 0, 300, 400))
//                .with(scale(imageView, "scaleX", 1, 3f, 700, 400))
//                .with(scale(imageView, "scaleY", 1, 3f, 700, 400));
//
//        animatorSet = getAnimatorSet(imageView);
//        animatorSet.start();
//        animatorSet.addListener(new AnimatorListenerAdapter() {
//            @Override
//            public void onAnimationEnd(Animator animation) {
//                super.onAnimationEnd(animation);
//                removeViewInLayout(imageView);
//            }
//        });
        return super.onTouchEvent(event);
    }

    private AnimatorSet getAnimatorSet(ImageView iv) {

        // 1.alpha动画
        ObjectAnimator alpha = ObjectAnimator.ofFloat(iv, "alpha", 1.5f, 0.3f);

        // 2.缩放动画
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(iv, "scaleX", 1f, 0.2f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(iv, "scaleY", 1f, 0.2f);

        //3.随机角度
        ObjectAnimator rotation =rotation(iv, 0, 0, num[new Random().nextInt(4)]);
        // 动画集合
        AnimatorSet set = new AnimatorSet();
        set.playTogether(alpha, scaleX, scaleY,rotation);
        set.setDuration(2000);

        // 贝塞尔曲线动画
        ValueAnimator bzier = getBzierAnimator(iv);

        AnimatorSet set2 = new AnimatorSet();
        set2.playTogether(set, bzier);
        set2.setTarget(iv);
        return set2;
    }


    /**
     * 贝塞尔动画
     */
    private ValueAnimator getBzierAnimator(final ImageView iv) {
        // TODO Auto-generated method stub
        PointF[] PointFs = getPointFs(iv); // 4个点的坐标
        for (int i=0;i<PointFs.length;i++){
            Log.d("tgw4个点的坐标", "onTouchEvent: mWidth:"+PointFs[i].x+"--mHeight:"+PointFs[i].y);
        }
        BasEvaluator evaluator = new BasEvaluator(PointFs[1], PointFs[2]);
        ValueAnimator valueAnim = ValueAnimator.ofObject(evaluator, PointFs[0], PointFs[3]);
        valueAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // TODO Auto-generated method stub
                PointF p = (PointF) animation.getAnimatedValue();
                iv.setX(p.x);
                iv.setY(p.y);
                iv.setAlpha(1 - animation.getAnimatedFraction()); // 透明度

            }
        });
        valueAnim.setTarget(iv);
        Interpolator interpolator = new LinearInterpolator();
        valueAnim.setDuration(2000);
        valueAnim.setInterpolator(interpolator);
//        valueAnim.setInterpolator(interpolators[new Random().nextInt(4)]);
        return valueAnim;
    }

    private PointF[] getPointFs(ImageView iv) {
        // TODO Auto-generated method stub
        PointF[] PointFs = new PointF[4];
        PointFs[0] = new PointF(); // p0
        PointFs[0].x = ((int) mWidth);
        PointFs[0].y = mHeight;

        PointFs[1] = new PointF(); // p1
        PointFs[1].x = new Random().nextInt(mWidth);
        PointFs[1].y = new Random().nextInt(mHeight / 2) + mHeight / 2;

        PointFs[2] = new PointF(); // p2
        PointFs[2].x = new Random().nextInt(mWidth);
        PointFs[2].y = new Random().nextInt(mHeight / 2);

        PointFs[3] = new PointF(); // p3
        PointFs[3].x = new Random().nextInt(mWidth);
//        PointFs[3].x = new Random().nextInt(mWidth);   PointFs[3].设置0永远左上角
        PointFs[3].y = 0;
        return PointFs;
    }

    public static ObjectAnimator scale(View view, String propertyName, float from, float to, long time, long delayTime) {
        ObjectAnimator translation = ObjectAnimator.ofFloat(view
                , propertyName
                , from, to);
        translation.setInterpolator(new LinearInterpolator());
        translation.setStartDelay(delayTime);
        translation.setDuration(time);
        return translation;
    }

    public static ObjectAnimator translationX(View view, float from, float to, long time, long delayTime) {
        ObjectAnimator translation = ObjectAnimator.ofFloat(view
                , "translationX"
                , from, to);
        translation.setInterpolator(new LinearInterpolator());
        translation.setStartDelay(delayTime);
        translation.setDuration(time);
        return translation;
    }

    public static ObjectAnimator translationY(View view, float from, float to, long time, long delayTime) {
        ObjectAnimator translation = ObjectAnimator.ofFloat(view
                , "translationY"
                , from, to);
        translation.setInterpolator(new LinearInterpolator());
        translation.setStartDelay(delayTime);
        translation.setDuration(time);
        return translation;
    }

    public static ObjectAnimator alpha(View view, float from, float to, long time, long delayTime) {
        ObjectAnimator translation = ObjectAnimator.ofFloat(view
                , "alpha"
                , from, to);
        translation.setInterpolator(new LinearInterpolator());
        translation.setStartDelay(delayTime);
        translation.setDuration(time);
        return translation;
    }

    public static ObjectAnimator rotation(View view, long time, long delayTime, float... values) {
        ObjectAnimator rotation = ObjectAnimator.ofFloat(view, "rotation", values);
        rotation.setDuration(time);
        rotation.setStartDelay(delayTime);
        rotation.setInterpolator(new TimeInterpolator() {
            @Override
            public float getInterpolation(float input) {
                return input;
            }
        });
        return rotation;
    }
}